package com.iwe.crm.user.controller;

import com.iwe.crm.base.bean.ResultVo;
import com.iwe.crm.base.exception.CrmEnum;
import com.iwe.crm.base.exception.CrmException;
import com.iwe.crm.base.util.CommonUtil;
import com.iwe.crm.base.util.FileUploadUtil;
import com.iwe.crm.user.bean.User;
import com.iwe.crm.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    //登录功能
    @PostMapping("/login")
    public ResultVo login(User user, HttpServletRequest request, HttpSession session){
        ResultVo resultVo = new ResultVo();
        try{
            //获取用户IP地址
            String remoteAddr = request.getRemoteAddr();
            user.setAllowIps(remoteAddr);
            user = userService.login(user);
            resultVo.setOk(true);
            //把用户存储到session中
            session.setAttribute("user",user);
        }catch (CrmException e){
          resultVo.setMessage(e.getMessage());
        }
        return resultVo;
    }

    //校验原始密码输入是否正确
    @PostMapping("/verifyOldPwd")
    public ResultVo verifyOldPwd(String oldPwd,HttpSession session){
        //取出Session用户
        User user = (User) session.getAttribute("user");
        ResultVo resultVo = new ResultVo();
        try{
           userService.verifyOldPwd(oldPwd,user);
            resultVo.setOk(true);
        }catch (CrmException e){
            resultVo.setMessage(e.getMessage());
        }
        return resultVo;
    }

    //上传头像
    @PostMapping("/fileUpload")
    public ResultVo fileUpload(HttpServletRequest request,MultipartFile file){
       return FileUploadUtil.fileUpload(file,request);
    }

    @PostMapping("/updateUser")
    public ResultVo updateUser(User user,HttpSession session){
        User user1 = CommonUtil.getCurrentUser(session);
        user.setId(user1.getId());
        ResultVo resultVo = new ResultVo();
        try{
            userService.updateUser(user);
            resultVo.setOk(true);
            resultVo.setMessage("更细用户信息成功");
        }catch (CrmException e){
            resultVo.setMessage(e.getMessage());
        }
        return resultVo;
    }
}
